package com.meiyu.live.ui.main.widget;

import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.android.volley.Response;
import com.google.gson.Gson;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.meiyu.live.BaseActivity;
import com.meiyu.live.BaseApplication;
import com.meiyu.live.R;
import com.meiyu.live.net.param.IndexFilterCountParams;
import com.meiyu.live.net.response.HotLiveResponse;
import com.meiyu.live.popj.Assort;
import com.meiyu.live.popj.CityListBean;
import com.meiyu.live.ui.columnfollow.ColumnFollowView;
import com.meiyu.live.util.DisplayUtils;
import com.meiyu.live.widget.WheelView;
import com.meiyu.live.widget.XCFlowLayout;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class ColumnDetailDrawerView extends FrameLayout implements View.OnClickListener {

    private TextView tv_location, tv_tvcount;
    private View btn_reset, btn_ok;
    private WheelView wv_province, wv_city;
    private XCFlowLayout flowLayout_type;
    private TextView tv_rank[];

    private static final int[][] rank_range = {
            {1, 50},
            {51, 100},
            {101, 200},
            {201, 300}
    };

    private ImageLoader imageLoader;
    private DisplayImageOptions options;
    private LayoutInflater inflater;
    private ViewGroup.MarginLayoutParams lp;

    private ArrayList<String> provinceList = new ArrayList<>();
    private CityListBean cityListBean;
    private List<Assort> typeList;

    private FilterViewListener filterViewListener;

    private BaseActivity activity;
    private long column_id;

    private long type_id = -1;
    private int[] range = rank_range[0];

    public interface FilterViewListener {
        void onClickOk(String location, long type, int[] range);
    }

    public ColumnDetailDrawerView(Context context) {
        super(context);
        init(context);
    }

    public ColumnDetailDrawerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public ColumnDetailDrawerView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context);
    }

    private void init(Context context) {
        activity = (BaseActivity) context;
        lp = new ViewGroup.MarginLayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lp.leftMargin = DisplayUtils.dpToPixel(getContext(), 5);
        lp.rightMargin = lp.leftMargin;
        lp.topMargin = lp.rightMargin;
        lp.bottomMargin = lp.topMargin;
        inflater = LayoutInflater.from(context);
        imageLoader = ImageLoader.getInstance();
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(R.drawable.image_loading)          // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.drawable.image_loading)  // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.drawable.image_loading)       // 设置图片加载或解码过程中发生错误显示的图片
                .cacheInMemory(true)                        // 设置下载的图片是否缓存在内存中
                .cacheOnDisk(true)                          // 设置下载的图片是否缓存在SD卡中
                .build();
        LayoutInflater inflater = LayoutInflater.from(context);
        inflater.inflate(R.layout.view_columndrawer, this);

        tv_location = (TextView) findViewById(R.id.tv_location);
        if (BaseApplication.getApp().getMlocation() != null) {
            String city = BaseApplication.getApp().getMlocation().getCity();
            if (!TextUtils.isEmpty(city)) {
                tv_location.setText(city);
            }
        }
        tv_tvcount = (TextView) findViewById(R.id.tv_tvcount);

        wv_province = (WheelView) findViewById(R.id.wv_province);
        wv_province.setTextSize(16);
        wv_city = (WheelView) findViewById(R.id.wv_city);
        wv_city.setTextSize(16);

        flowLayout_type = (XCFlowLayout) findViewById(R.id.flowLayout_type);

        tv_rank = new TextView[]{
                (TextView) findViewById(R.id.tv_rank0),
                (TextView) findViewById(R.id.tv_rank1),
                (TextView) findViewById(R.id.tv_rank2),
                (TextView) findViewById(R.id.tv_rank3)
        };
        for (TextView textView : tv_rank) {
            textView.setOnClickListener(onClickListener_range);
        }

        btn_reset = findViewById(R.id.btn_reset);
        btn_reset.setOnClickListener(this);
        btn_ok = findViewById(R.id.btn_ok);
        btn_ok.setOnClickListener(this);

        getCityList();
    }

    private OnClickListener onClickListener_range = new OnClickListener() {
        @Override
        public void onClick(View view) {
            for (int i = 0; i < tv_rank.length; i++) {
                if (tv_rank[i] == view) {
                    tv_rank[i].setBackgroundResource(R.drawable.background_columnfollowview_s);
                    range = rank_range[i];
                } else {
                    tv_rank[i].setBackgroundResource(R.drawable.background_columnfollowview_n);
                }
            }
            getData();
        }
    };

    private void getCityList() {
        try {
            InputStream inputStream = getResources().getAssets().open("citylist.json");
            Scanner scanner = new Scanner(inputStream, "UTF-8");
            String jsonString = scanner.useDelimiter("\\A").next();
            scanner.close();
            inputStream.close();

            cityListBean = new Gson().fromJson(jsonString, CityListBean.class);

            for (CityListBean.Province province : cityListBean.getProvinceList()) {
                provinceList.add(province.getKey());
            }

            wv_province.setItems(provinceList);
            wv_province.setSeletion(0);
            wv_city.setItems(cityListBean.getProvinceList().get(0).getCityList());

            wv_province.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
                @Override
                public void onSelected(int selectedIndex, String item) {
                    int index = selectedIndex - 1;
                    if (index >= 0 && index < provinceList.size()) {
                        wv_city.setItems(cityListBean.getProvinceList().get(index).getCityList());
                        wv_city.setSeletion(0);
                    }
                }
            });
            wv_city.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
                @Override
                public void onSelected(int selectedIndex, String item) {
                    tv_location.setText(item);
                    getData();
                }
            });

        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {

        }

    }

    public void setTypeData(List<Assort> typeList) {
        if (typeList != null) {
            this.typeList = typeList;
            flowLayout_type.removeAllViews();
            for (Assort bean : typeList) {
                final ColumnFollowView followView = new ColumnFollowView(getContext());
                followView.setOnClickListener(onClickListener_type);
                followView.setData(bean);
                followView.update();
                flowLayout_type.addView(followView, lp);
            }

        }
    }

    private OnClickListener onClickListener_type = new OnClickListener() {
        @Override
        public void onClick(View view) {
            for (int i = 0; i < flowLayout_type.getChildCount(); i++) {
                ColumnFollowView followView = (ColumnFollowView) flowLayout_type.getChildAt(i);
                if (view == followView) {
                    followView.getData().isSelected = !followView.getData().isSelected;
                    if (followView.getData().isSelected) {
                        type_id = typeList.get(i).getId();
                    } else {
                        type_id = -1;
                    }
                } else {
                    followView.getData().isSelected = false;
                }
                followView.update();
                getData();
            }
        }
    };

    public void setFilterViewListener(FilterViewListener filterViewListener) {
        this.filterViewListener = filterViewListener;
    }

    @Override
    public void onClick(View view) {
        if (view == btn_reset) {
            //重置地址
            if (BaseApplication.getApp().getMlocation() != null) {
                String city = BaseApplication.getApp().getMlocation().getCity();
                if (!TextUtils.isEmpty(city)) {
                    tv_location.setText(city);
                }
            }
            //重置标签
            int childCounts = flowLayout_type.getChildCount();
            for (int i = 0; i < childCounts; i++) {
                ColumnFollowView followView = (ColumnFollowView) flowLayout_type.getChildAt(i);
                followView.getData().isSelected = false;
                followView.update();
            }
            type_id = -1;
            //重置范围
            for (int i = 0; i < tv_rank.length; i++) {
                if (i == 0) {
                    tv_rank[i].setBackgroundResource(R.drawable.background_columnfollowview_s);
                    range = rank_range[i];
                } else {
                    tv_rank[i].setBackgroundResource(R.drawable.background_columnfollowview_n);
                }
            }
        } else if (view == btn_ok) {
            if (filterViewListener != null) {
                filterViewListener.onClickOk(tv_location.getText().toString(), type_id, range);
            }
        }
    }

    public void setColumnId(long column_id) {
        this.column_id = column_id;
    }

    private void getData() {
        //如果用户未在界面选择，三个参数都有默认值，location为当前城市，
        //sl_assort_id第一位为首页选中的一级类别，第二位为当前界面选中的二级类别，如未选择，则没有第二个元素
        //rows默认值为｛1，50｝
        activity.request(new IndexFilterCountParams(1), HotLiveResponse.class, new Response.Listener<HotLiveResponse>() {
            @Override
            public void onResponse(HotLiveResponse hotLiveResponse) {
                tv_tvcount.setText(hotLiveResponse.getMsg());
            }
        });
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        super.dispatchTouchEvent(ev);
        return true;
    }
}
